﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MapHello.Core
{
    static class TaskManagement
    {
        public static bool IsSystemTaskActive { get; set; }

        private static List<AsyncTask> m_taskContainer;


        static TaskManagement()
        {
            m_taskContainer = new List<AsyncTask>();
        }

        public static void RunTask(AsyncTask taskItem)
        {
            m_taskContainer.Add(taskItem);
            Task task = new Task(() =>
            {
                Thread.Sleep(taskItem.Interval);
                if (TaskState.Stop != taskItem.TaskState)
                {
                    taskItem.TaskState = TaskState.Executing;
                    try
                    {
                        taskItem.Run(taskItem.State);
                        taskItem.NotifyCompletion();

                        taskItem.TaskState = TaskState.Done;
                    }
                    catch (Exception e)
                    {
                        taskItem.TaskState = TaskState.Error;
                        taskItem.Exception = e;

                        Debug.WriteLine("Task Error - {0}: {1}", taskItem.GetType(), e);
                    }
                    finally
                    {
                        taskItem.Dispose();
                    }
                }

                if (m_taskContainer.Contains(taskItem))
                {
                    m_taskContainer.Remove(taskItem);
                }
            });

            task.Start();
        }

        public static void Stop()
        {
            foreach (AsyncTask item in m_taskContainer)
            {
                item.TaskState = TaskState.Stop;
                if (item.TaskState == TaskState.Sleep)
                {
                    m_taskContainer.Remove(item);
                }
            }
        }
    }
}
